﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using com.kmer.Cache;
using com.kmer.Helper;
using kmer.Web.Helper;

// ReSharper disable CheckNamespace
namespace com.kmer.ApiServer {
	/// <summary>
	/// 用来处理多API合并调用
	/// </summary>
	public class CoreHandler : BaseHandler {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="jsonData"></param>
		/// <param name="type"></param>
		/// <returns></returns>
		[JSONData]
        [Description("处理多API合并调用")]
        [ReturnType(typeof(IList<InitResult>),"多个API的返回数据集合")]
        [ApiVersion("1.3.0")]
        public ApiResult Init(string jsonData, int type = 1) {
			var param = type == 2 ? GetData<InitParam>(jsonData) : QueryStringHelper.ParseQuery<InitParam>(jsonData);
			var result = new List<InitResult>();
			foreach (var item in param.args) {
				var handler = APIHandlerFactory.getHandler(item.controller + "Handler");
				if (handler == null) {
					result.Add(new InitResult() {
						ID = item.ID,
						Result = Error("调用" + item.controller + "时发生错误")
					});
				} else {
					try {
						var r = handler.Execute(Context, item.action, item.data);
						result.Add(new InitResult() {
							ID = item.ID,
							Result = r
						});
					} catch (Exception ex) {
						result.Add(new InitResult() {
							ID = item.ID,
							Result = Error(ex)
						});
					}
				}
			}

			return Success(result);
		}

        

        #region Data
        /// <summary>
        /// 初始化之后返回的数据结构类
        /// </summary>
        public class InitResult {
			/// <summary>
			/// 唯一ID
			/// </summary>
			[ParamDescription("客户端请求时提交的ID")]
            public long ID { get; set; }
			/// <summary>
			/// 结果
			/// </summary>
			[ParamDescription("API返回结果，不同的API返回的数据不同")]
            public object Result { get; set; }
		}
		/// <summary>
		/// 初始化API的输入参数
		/// </summary>
		public class InitParam {
			/// <summary>
			/// 参数列表
			/// </summary>
			public List<InitParamItem> args { get; set; }
		}
		/// <summary>
		/// 
		/// </summary>
		public class InitParamItem {
			/// <summary>
			/// 要调用的控制器
			/// </summary>
			public string controller { get; set; }
			/// <summary>
			/// 要调用的动作
			/// </summary>
			public string action { get; set; }
			/// <summary>
			/// 输入的参数
			/// </summary>
			public string data { get; set; }
			/// <summary>
			/// 唯一ID
			/// </summary>
			public long ID { get; set; }
		}
        
        #endregion
    }
}
